package com.adcc.loadsheet.monitor.service;

import com.adcc.aoc.devLib.common.codec.MD5;
import com.adcc.aoc.devLib.common.log.Log;
import com.adcc.loadsheet.monitor.entity.User;
import com.adcc.loadsheet.monitor.util.Constant;
import com.adcc.loadsheet.monitor.util.UserFactory;
import com.google.common.base.Optional;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service("LoginService")
public class LoginServiceImpl implements LoginService {

    @Autowired
    private UserFactory userFactory;

    @Override
    public Optional<User> verifyUser(String username, String password) {
        try {
            User user = new User();
            String adminUserName = userFactory.getAdminUserName();
            String operatorUserName = userFactory.getOperatorUserName();
            if(adminUserName.equals(username)) {
                String adminPassword = userFactory.getAdminPassword();
                if(MD5.isPasswordValid(adminPassword, password, userFactory.getSaltValue())){
                    user.setUsername(adminUserName);
                    user.setPassword(adminPassword);
                    user.setRole(0);
                    user.setCode(0);
                    user.setLoginTime(DateTime.now(DateTimeZone.UTC).toString("yyyy-MM-dd HH:mm:ss"));
                }else{
                    user.setCode(-1);
                    user.setReason(Constant.ERROR_LOGIN_PASSWORD);
                }
            } else if(operatorUserName.equals(username)){
                String operatorPassword = userFactory.getOperatorPassword();
                if(MD5.isPasswordValid(operatorPassword, password, userFactory.getSaltValue())){
                    user.setUsername(operatorUserName);
                    user.setPassword(operatorPassword);
                    user.setRole(1);
                    user.setCode(0);
                    user.setLoginTime(DateTime.now(DateTimeZone.UTC).toString("yyyy-MM-dd HH:mm:ss"));
                }else{
                    user.setCode(-1);
                    user.setReason(Constant.ERROR_LOGIN_PASSWORD);
                }
            } else {
                user.setCode(-1);
                user.setReason(Constant.ERROR_LOGIN_USERNAME);
            }
            return Optional.of(user);
        } catch (Exception ex) {
            Log.error(LoginService.class, "verifyUser() error", ex);
            return Optional.absent();
        }

    }
}
